import React, { PureComponent } from 'react'
import {
  message, Button, Alert, Popconfirm,
} from 'antd'
import { connect } from '@umijs/max'
import { ProTable, ProTableOperate, ProTableOptions } from '@/components'
import styles from './index.less'
import SecretKeyModal from './secretKeyModal'
import { getAKList, delAK, editAKDes, addAKSK, editAKStatus } from './api'

const { OperateItem } = ProTableOperate

@connect(({ global }) => ({ ...global }))
class SecretKey extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      akList: [],
      visibleDelete: false,
      deleteId: null,
      currentRecord: null,
      query: {},
    }
    this.secretKeyModalRef = React.createRef()
  }

  componentDidMount() {
    this.fetchAKList()
  }

  fetchData = async () => {
    const { accessKey } = this.state
    const tempQuery = {}
    if (accessKey && accessKey !== '') tempQuery.accessKey = accessKey
    this.setState({
      query: tempQuery,
    })
  }
  // 获取密钥列表
  fetchAKList = () => {
    this.setState({ loading: true })
    const {query} = this.state
    getAKList(query).then((res) => {
      const akList = Array.isArray(res.result) ? res.result : []
      this.setState({ akList, loading: false })
    }).catch(error => {
      console.error(error)
      message.error('获取密钥列表失败')
      
    }).finally(() => {
        this.setState({ loading: false })
    })
  }

  // 执行删除操作
  onDeleteClick = (accessKey) => {
    this.setState({ loading: true })
    delAK(accessKey).then(() => {
        message.success('删除密钥成功')
        this.fetchData()
        this.fetchAKList()
      },
      (error) => {
        console.log(error)
        this.setState({ loading: false })
      }
    )
  }

  editStatus = (accessKey) => {
    this.setState({ loading: true })

    // 调用编辑状态的 API，传递参数
    editAKStatus( accessKey ).then(() => {
      message.success('状态更新成功')
      this.fetchAKList()
    }).catch(error => {
      console.error(error)
      message.error('状态更新失败')
    }).finally(() => {
      this.setState({ loading: false })
    })
  }

  showSecretKeyModal = () => {
    this.setState({ currentRecord: null }, () => {
      this.secretKeyModalRef.current.openModal() // 开启创建密钥的弹窗
    })
  }

  // 创建或编辑密钥的提交处理
  handleSecretKeySubmit = (values) => {
    this.setState({ loading: true })
    const { currentRecord } = this.state

    return new Promise(async (resolve, reject) => {
        try {
            if (currentRecord) {
                await editAKDes({ accessKey: currentRecord.accessKey, description: values.description })
                message.success('编辑密钥描述成功')
            } else {
                await addAKSK({ description: values.description })
                message.success('创建密钥成功')
            }
            this.fetchAKList()
            this.secretKeyModalRef.current.closeModal()
            resolve()
        } catch (error) {
            console.error(error)
            // message.error(currentRecord ? '编辑密钥描述失败' : '创建密钥失败')
            reject(error)
        } finally {
            this.setState({ loading: false })
        }
    })
}


  render() {
    const { loading, akList, visibleDelete } = this.state

    return (
      <div className={styles.secret_key_page}>
        <div className={styles.secret_key_title}>访问密钥</div>
        <ProTableOperate toggleOperate={false} unfolded>
          <OperateItem align="left">
            <Alert message="同一时间只允许存在一个访问密钥" type="info" showIcon />
          </OperateItem>
          <OperateItem itemType="btn">
            <Button 
            type="primary" onClick={this.showSecretKeyModal}>创建密钥
            </Button>
          </OperateItem>
        </ProTableOperate>
        <ProTable
          dataSource={akList}
          loading={loading}
          columns={[
            {
              title: '密钥ID',
              dataIndex: 'accessKey',
              width: '10%',
              key: 'accessKey',
            },
            {
              title: '描述',
              dataIndex: 'description',
              width: '10%',
              key: 'description',
            },
            {
              title: '状态',
              dataIndex: 'enabled',
              width: '20%',
              key: 'enabled',
              render: (text) => (text === 1 ? '启用' : '停用'),
            },
            {
              title: '创建时间',
              dataIndex: 'createTime',
              width: '20%',
              key: 'createTime',
              render: (text) => (!text ? '--' : text),
            },
            {
              title: '最近使用时间',
              dataIndex: 'updateTime',
              width: '10%',
              key: 'updateTime',
            },
            {
              title: '操作',
              dataIndex: 'operation',
              width: '15%',
              key: 'operation',
              render: (text, record) => (
                <ProTableOptions>
                  <span key="edit" onClick={() => {
                    this.setState({ currentRecord: record }, () => {
                      this.secretKeyModalRef.current.openEditModal(record)
                    })
                  }}>
                    编辑
                  </span>
                  <span key="toggle" onClick={() => {
                    this.editStatus(record.accessKey)
                  }}>
                    {record.enabled === 1 ? '停用' : '启用'}
                  </span>
                  <Popconfirm
                    title="确定要删除吗？"
                    onConfirm={() => this.onDeleteClick(record.accessKey)}
                    okText="是"
                    cancelText="否"
                  >
                    <span>删除</span>
                  </Popconfirm>
                </ProTableOptions>
              ),
            },
          ]}
        />
        <SecretKeyModal 
          ref={this.secretKeyModalRef}
          onSubmit={this.handleSecretKeySubmit} // 提交回调
        />
      </div>
    )
  }
}

export default SecretKey
